package com.ibm.crl.sb.thread.typicalexam.philosophers;

/**
 * 哲学家进餐问题
 * 
 * 会引发死锁
 * 
 * @author soft
 * 
 */
class kuai {

	String name;
	boolean Enable = true;

	public kuai(String name) {
		this.name = name;
	}

	public synchronized void pickup() {

		this.Enable = false;

	}

	public synchronized void putdown() {
		this.Enable = true;
		this.notifyAll();
	}
}

class Philosopher extends Thread {
	String name;
	kuai left;
	kuai right;

	public Philosopher(String name, kuai l, kuai r) {
		this.name = name;
		left = l;
		right = r;
	}

	public void run() {
		if (left.Enable) {
			left.pickup();
		} else {
			while (!left.Enable) {
				try {
					System.out.println(name + " 在等待 " + left.name);
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		System.out.println(name + " 眼明手快，以迅雷不及掩耳之势一把抓起 " + left.name);

		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		if (right.Enable) {
			right.pickup();
		} else {
			while (!left.Enable) {
				try {
					System.out.println(name + "在等待 " + right.name);
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}

		System.out.println(name + " 眼明手快，以迅雷不及掩耳之势一把抓起 " + right.name);
		System.out.println(name + " 左右开弓，狼吞虎咽起来");

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(name + " 酒足饭饱，打了个饱嗝，心满意足的放下了 " + left.name + " 和 "
				+ right.name);
		left.putdown();
		right.putdown();
	}
}

public class EatError {
	public static void main(String args[]) {
		kuai k1 = new kuai("筷子1号");
		kuai k2 = new kuai("筷子2号");
		kuai k3 = new kuai("筷子3号");
		kuai k4 = new kuai("筷子4号");
		kuai k5 = new kuai("筷子5号");
		Philosopher p1 = new Philosopher("老大", k1, k2);
		Philosopher p2 = new Philosopher("老二", k2, k3);
		Philosopher p3 = new Philosopher("老三", k3, k4);
		Philosopher p4 = new Philosopher("老四", k4, k5);
		Philosopher p5 = new Philosopher("老幺", k5, k1);
		p1.start();
		p2.start();
		p3.start();
		p4.start();
		p5.start();
	}
}